import { getloginPages } from "@/utils/pages";
import wechatOa from "@/utils/wechat";
import { lang} from '@/locale';
import { getToken } from "@/stores/auth";
import { getChannel } from "@/utils/channel";
import { ChannelEnum } from "@/enums/channelEnum";

const routeInterceptor = () => {
    // 获取登录页面
    const needLoginList = getloginPages();

    // 初始化验证
    const launch = uni.getLaunchOptionsSync();
    const path = `/${launch.path}`; //页面路径

    // 加载插件语言
    lang.loadAddonLocaleLang(launch.path, uni.getLocale());

    // 登录检验
    checkNeedLogin(path, needLoginList);

    // 添加路由拦截器
    const list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
    list.forEach((item) => {
        uni.addInterceptor(item, {
            invoke(e) {
                // 跳转页面登录验证
                const url = e.url.split("?")[0]; //获取当前页面路径（即url去掉"?"和"?"后的参数）
                return checkNeedLogin(url, needLoginList);
            },
            fail(err) {
                // 失败回调拦截
                console.log(err);
            },
        });
    });

    // #ifdef H5
    setTimeout(async () => {
        // 微信jssdk初始化
        if (getChannel() == ChannelEnum.WX_OA && getToken()) await wechatOa.config();
    });

    uni.getSystemInfoSync().platform == "ios" &&
        uni.setStorageSync("appIosUrl", location.href);
    // #endif
};

// 登录验证
const checkNeedLogin = (url: string, needLoginList: any) => {
    // 判断要打开的页面是否需要验证登录
    if (needLoginList.includes(url) && (!getToken())) {
        uni.navigateTo({
            url: "/pages/login/login",
        });
        return false;
    } else {
        return true;
    }
};

export default routeInterceptor;
